package com.chen.androidstudy.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

public class AudioFormatExampleUtil {
    public static String getAudioFormat(String filePath) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            String mimeType = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            String audioFormat = "";
            Log.e("chen", "Audio mimeType: " + mimeType);
            if (mimeType != null) {
                audioFormat = mimeType.substring(mimeType.indexOf("/") + 1);
                Log.e("chen", "Audio format: " + audioFormat);
            } else {
                Log.e("chen", "Unable to determine audio format");
            }
            String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/2";
            return audioFormat;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    public static String getAudioFormat2(Context context) {
        ContentResolver contentResolver = context.getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = {MediaStore.Audio.Media._ID, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.MIME_TYPE,
                };
        Cursor cursor = contentResolver.query(uri, projection, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                int columnIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
                long id = cursor.getLong(columnIndex);
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
                String MIME_TYPE = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.MIME_TYPE));
//                String CONTENT_TYPE = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.CONTENT_TYPE));
//                String ENTRY_CONTENT_TYPE = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ENTRY_CONTENT_TYPE));
// 在这里可以处理获取到的音频文件信息
                Log.e("chen", path +" " + MIME_TYPE );
//                String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/2";
//                new DownloadAndConvertTask(dir).execute(path);

            }
            cursor.close();
        }
        return "";
    }
}